document.addEventListener('DOMContentLoaded', () => {
    // 加载保存的设置
    chrome.storage.sync.get(['baseUrl', 'apiKey', 'model', 'classifyMode', 'reclassify', 'saveFolder'], (data) => {
        if (data.baseUrl) document.getElementById('baseUrl').value = data.baseUrl;
        if (data.apiKey) document.getElementById('apiKey').value = data.apiKey;
        if (data.model) document.getElementById('model').value = data.model;
        if (data.classifyMode) document.getElementById('classifyMode').value = data.classifyMode;
        else document.getElementById('classifyMode').value = 'one_by_one'; // 默认使用逐个分类
        if (data.reclassify) document.getElementById('reclassify').value = data.reclassify;
        else document.getElementById('reclassify').value = 'false'; // 默认跳过已分类书签
        if (data.saveFolder) document.getElementById('saveFolder').value = data.saveFolder;
        else document.getElementById('saveFolder').value = 'AI分类'; // 默认文件夹名称
    });

    // 侧边栏导航功能
    const navItems = document.querySelectorAll('.nav-item');
    const sections = document.querySelectorAll('.content-section');

    function switchSection(sectionId) {
        // 隐藏所有section
        sections.forEach(section => section.classList.add('hidden'));
        // 显示目标section
        document.getElementById(sectionId).classList.remove('hidden');
        // 更新导航项的激活状态
        navItems.forEach(item => {
            if (item.getAttribute('data-section') === sectionId) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        });
    }

    // 为每个导航项添加点击事件
    navItems.forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            const sectionId = item.getAttribute('data-section');
            switchSection(sectionId);
        });
    });

    // 自动保存功能
    const inputs = document.querySelectorAll('input, select');
    inputs.forEach(input => {
        input.addEventListener('change', () => {
            const settings = {
                baseUrl: document.getElementById('baseUrl').value.trim(),
                apiKey: document.getElementById('apiKey').value.trim(),
                model: document.getElementById('model').value,
                classifyMode: document.getElementById('classifyMode').value,
                reclassify: document.getElementById('reclassify').value,
                saveFolder: document.getElementById('saveFolder').value.trim() || 'AI分类'
            };

            chrome.storage.sync.set(settings, () => {
                // 可以添加一个临时的保存成功提示
                const savedIndicator = document.createElement('div');
                savedIndicator.textContent = '✓ 已保存';
                savedIndicator.style.cssText = `
                    position: fixed;
                    bottom: 20px;
                    right: 20px;
                    background: var(--primary-color);
                    color: white;
                    padding: 8px 16px;
                    border-radius: 8px;
                    font-size: 14px;
                    opacity: 0;
                    transition: opacity 0.3s ease;
                `;
                document.body.appendChild(savedIndicator);

                // 显示提示
                setTimeout(() => savedIndicator.style.opacity = '1', 0);
                
                // 3秒后淡出并移除
                setTimeout(() => {
                    savedIndicator.style.opacity = '0';
                    setTimeout(() => savedIndicator.remove(), 300);
                }, 2000);
            });
        });
    });

    // API测试功能
    async function testAPI() {
        const baseUrl = document.getElementById('baseUrl').value.trim();
        const apiKey = document.getElementById('apiKey').value.trim();
        const model = document.getElementById('model').value;

        if (!baseUrl || !apiKey || !model) {
            alert('请填写完整的 API 配置信息');
            return;
        }

        try {
            const response = await fetch(`${baseUrl}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    model: model,
                    messages: [{ role: 'user', content: '你好' }],
                    max_tokens: 5
                })
            });

            const result = await response.json();

            if (response.ok && result.choices) {
                alert('API 连接成功！模型可用 ✅');
            } else {
                throw new Error(result.error?.message || `请求失败: ${response.status}`);
            }
        } catch (error) {
            alert('API 连接失败 ❌\n' + error.message);
            console.error(error);
        }
    }

    // 添加API测试按钮（如果需要）
    const apiTestButton = document.createElement('button');
    apiTestButton.textContent = '测试 API 连接';
    apiTestButton.style.marginTop = '24px';
    document.querySelector('#basic .form-group').appendChild(apiTestButton);
    apiTestButton.addEventListener('click', testAPI);
});